import React, { useState } from "react";
import "./login.css";
import { notifications } from "../share/base.js";
import { checkAccount } from "./share.js";
import api from "../share/api.js";

function LoginForm() {
  const [account, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const handleLogin = async (e) => {
    e.preventDefault();
    // 在这里处理登录逻辑
    if (!checkAccount(account)) {
      const account = document.getElementById("account");
      account.value = "";
      account.setAttribute("placeholder", "try: 17312342347");
      notifications.show("please input a valid account!", "error");
      return;
    }
    const res = await api.login({
      account: account,
      password: password,
    });
    //console.log(res);
    if (!res.ok) {
      notifications.show(res.message, "error");
    } else {
      notifications.show("login success");
      window.location.href = "/home";
    }
  };

  return (
    <form>
      <div id="LoginDiv">
        <div>Welcome.</div>
        <input
          id="account"
          type="text"
          value={account}
          placeholder="Account"
          required
          onChange={(e) => {
            setUsername(e.target.value);
            if (!checkAccount(e.target.value)) e.target.classList.add("red");
            else e.target.classList.remove("red");
          }}
        />
        <br />
        <input
          type="password"
          value={password}
          placeholder="Password"
          required
          onChange={(e) => setPassword(e.target.value)}
        />
        <br />
        <button type="submit" onClick={handleLogin}>
          Login
        </button>
      </div>
    </form>
  );
}

export default LoginForm;
